package gw.com.android.ui.account;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.BtnClickListener;

/**
 * 修改密码界面
 * 
 * @author reeta
 * 
 */
public class ModifyPassActivity extends BaseActivity implements View.OnFocusChangeListener,TextWatcher {

	/** 原密码输入框 */
	@BindView(R.id.password_orgianl)
	EditText mOrgianlPwd;
	/** 新密码输入框 */
	@BindView(R.id.password_new)
	EditText mNewPwd;
	/** 确认密码输入框 */
	@BindView(R.id.password_confirm)
	EditText mConfirmPwd;
	@BindView(R.id.tips_layout)
	View mTipLayout;
	@BindView(R.id.password_tips_1)
	TextView mTipView1;
	@BindView(R.id.password_tips_2)
	TextView mTipView2;
	@BindView(R.id.password_tips_3)
	TextView mTipView3;

	private PopupConfirmDialog dialog;

	@Override
	protected int getLayoutView() {
		return R.layout.activity_login_change_pwd;
	}

	@Override
	protected void initLayoutView() {
		mTitleBar.setAppTitle(R.string.password_title);
		mOrgianlPwd.setOnFocusChangeListener(this);
		mNewPwd.setOnFocusChangeListener(this);
		mConfirmPwd.setOnFocusChangeListener(this);
		mNewPwd.addTextChangedListener(this);
		mTipLayout.setVisibility(View.GONE);
	}

	@Override
	protected void initViewData() {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		checkPassLevel(s.toString());
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		checkError(v.getId(), hasFocus);
	}

	/**
	 * 返回密码强度等级
	 * @param inputString
	 * @return
     */
	private int getPassLevel(String inputString){
		int level = AppContances.PASSWORD_LEVEL_NO;
		if (inputString.matches("^[0-9]{6,16}")
				|| inputString.matches("^[a-z]{6,16}")
				|| inputString.matches("^[A-Z]{6,16}")) {
			level = AppContances.PASSWORD_LEVEL_LOW;
		} else if (inputString.matches("^(?!([a-z]+|\\d+)$)[a-z\\d]{6,16}$")
				||inputString.matches("^(?!([A-Z]+|\\d+)$)[A-Z\\d]{6,16}$")
				|| inputString.matches("^(?!([a-z]+|[A-Z]+)$)[a-zA-Z]{6,16}$") ) {
			level = AppContances.PASSWORD_LEVEL_MID;
		}else if(inputString.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,16}$")){
			level = AppContances.PASSWORD_LEVEL_STRONG;
		}

		return level;
	}

	/**
	 * 检查设置密码的强度逻辑
	 * @param newPwd
	 * @return
     */
	private int checkPassLevel(String newPwd){
		int level = getPassLevel(newPwd);
		if (TextUtils.isEmpty(newPwd) || level == AppContances.PASSWORD_LEVEL_NO) {
			mTipLayout.setVisibility(View.GONE);
		}else{
			mTipLayout.setVisibility(View.VISIBLE);
			if(level == AppContances.PASSWORD_LEVEL_LOW){
				mTipView1.setTextColor(ColorThemeUtil.instance().color_e);
				mTipView1.setBackgroundColor(ColorThemeUtil.instance().color_code_a);
				mTipView2.setTextColor(ColorThemeUtil.instance().color_h);
				mTipView2.setBackgroundColor(ColorThemeUtil.instance().color_d);
				mTipView3.setTextColor(ColorThemeUtil.instance().color_h);
				mTipView3.setBackgroundColor(ColorThemeUtil.instance().color_d);
			}else if(level == AppContances.PASSWORD_LEVEL_MID){
				mTipView1.setTextColor(ColorThemeUtil.instance().color_e);
				mTipView1.setBackgroundColor(ColorThemeUtil.instance().color_code_a);
				mTipView2.setTextColor(ColorThemeUtil.instance().color_e);
				mTipView2.setBackgroundColor(ColorThemeUtil.instance().color_code_b);
				mTipView3.setTextColor(ColorThemeUtil.instance().color_h);
				mTipView3.setBackgroundColor(ColorThemeUtil.instance().color_d);
			}else if(level == AppContances.PASSWORD_LEVEL_STRONG){
				mTipView1.setTextColor(ColorThemeUtil.instance().color_e);
				mTipView1.setBackgroundColor(ColorThemeUtil.instance().color_code_a);
				mTipView2.setTextColor(ColorThemeUtil.instance().color_e);
				mTipView2.setBackgroundColor(ColorThemeUtil.instance().color_code_b);
				mTipView3.setTextColor(ColorThemeUtil.instance().color_e);
				mTipView3.setBackgroundColor(ColorThemeUtil.instance().color_code_c);
			}
		}

		return level;
	}

	/**
	 * 检查输入框错误
	 * @return
     */
	private boolean checkError(int viewId, boolean hasFocus){
		final String orgianlPwd = mOrgianlPwd.getText().toString();
		final String newPwd = mNewPwd.getText().toString();
		String confimtPwd = mConfirmPwd.getText().toString();
		// 为null或者""判断
		if(!hasFocus){
			//viewid为0时标识点击提交按钮之后的错误检查
			if(viewId == R.id.password_orgianl || viewId == 0){
				if (TextUtils.isEmpty(orgianlPwd)) {
					if(viewId == 0 ){
						showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1046));
						mOrgianlPwd.setBackgroundResource(R.drawable.common_corner_color_p);
						mOrgianlPwd.setTextColor(ColorThemeUtil.instance().color_p);
						return true;
					}
				} else if (!orgianlPwd.equals(GTConfig.instance().mUserPwd)) {
					showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1069));
					mOrgianlPwd.setBackgroundResource(R.drawable.common_corner_color_p);
					mOrgianlPwd.setTextColor(ColorThemeUtil.instance().color_p);
					return true;
				}

				mOrgianlPwd.setBackgroundResource(R.drawable.common_edittext_bg_selector);
				mOrgianlPwd.setTextColor(ColorThemeUtil.instance().color_b);
			}

			if(viewId == R.id.password_new || viewId == 0){
				int level = checkPassLevel(newPwd);
				if (TextUtils.isEmpty(newPwd)) {
					if(viewId == 0){
						showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1051));
						mNewPwd.setBackgroundResource(R.drawable.common_corner_color_p);
						mNewPwd.setTextColor(ColorThemeUtil.instance().color_p);
						return true;
					}
				}else if (level == AppContances.PASSWORD_LEVEL_NO || !newPwd.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$")) {
					showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1051));
					mNewPwd.setBackgroundResource(R.drawable.common_corner_color_p);
					mNewPwd.setTextColor(ColorThemeUtil.instance().color_p);
					return true;
				}
				mNewPwd.setBackgroundResource(R.drawable.common_edittext_bg_selector);
				mNewPwd.setTextColor(ColorThemeUtil.instance().color_b);
			}

			if(viewId == R.id.password_confirm || viewId == 0){
				if (TextUtils.isEmpty(confimtPwd) || TextUtils.isEmpty(newPwd)) {
					if(viewId == 0){
						showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1048));
						mConfirmPwd.setBackgroundResource(R.drawable.common_corner_color_p);
						mConfirmPwd.setTextColor(ColorThemeUtil.instance().color_p);
						return true;
					}
				}else if (!newPwd.equals(confimtPwd)) {
					showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1048));
					mConfirmPwd.setBackgroundResource(R.drawable.common_corner_color_p);
					mConfirmPwd.setTextColor(ColorThemeUtil.instance().color_p);
					return true;
				}
				mConfirmPwd.setBackgroundResource(R.drawable.common_edittext_bg_selector);
				mConfirmPwd.setTextColor(ColorThemeUtil.instance().color_b);
			}
		}

		return false;
	}

	/**
	 * 重置输入框
	 */
	@OnClick(R.id.reset_btn)
	void resetEditText() {
		mOrgianlPwd.setText("");
		mNewPwd.setText("");
		mConfirmPwd.setText("");
	}

	/**
	 * 忘记密码提交
	 */
	@OnClick(R.id.submit_btn)
	void updatePwdSubmit() {
		if(CommonUtils.isFastDoubleClick()){
			return;
		}

		// 未连上网络时,气泡提示
		if (!NetworkMonitor.hasNetWork()) {
			return;
		}

		if(checkError(0, false)){
			return;
		}

		showLoading();
		AppTerminal.instance().updatePassword(mOrgianlPwd.getText().toString(), mNewPwd.getText().toString());
	}

	@Override
	public void registerRxBus() {
		super.registerRxBus();
		Disposable modifyPassRegister = RxBus.getInstance().register(GTSConst.REPLY_HTTP_UPDATE_PASS+"", Bundle.class).observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Consumer<Bundle>(){

					@Override
					public void accept(@io.reactivex.annotations.NonNull Bundle bundle) throws Exception {
						hideLoading();
						int iValue = bundle.getInt("iValue");
						if(iValue == 0){
							dialog = PopupConfirmDialog.newInstance(ModifyPassActivity.this, ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1049),
									new BtnClickListener() {
										@Override
										public void onBtnClick(int viewID) {
											if (viewID == R.id.action_btn_pos) {
												//修改密码成功退到登陆界面,密码置为空
												GTConfig.instance().mUserPwd = "";
												GTConfig.instance().saveLoginInfo(GTConfig.instance().getLoginName(), "");
												ActivityManager.backLogin(ModifyPassActivity.this, true);
											}
										}
									});
							dialog.setCancelable(false);
							dialog.show();
						}else{
							String result = bundle.getString("strObject");
							Logger.i("修改密码失败通知  iValue " + iValue + ", strObject = "+ result);

							showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(iValue+""));
						}
					}
				});

		bindSubscription(modifyPassRegister);
	}

}
